package redis

import (
	"context"
	"fmt"
	"time"

	"github.com/go-redis/redis/v8"
)

var ctx = context.Background()
var client *redis.Client = nil

type Config struct {
	Address  string // 地址
	Password string // 密码
	Db       int    // 数据库
}

func Set(key string, value interface{}, expiration time.Duration) error {
	err := client.Set(ctx, key, value, expiration).Err()
	if err != nil {
		return err
	}
	return nil
}

func Get(key string) (interface{}, error) {
	val, err := client.Get(ctx, key).Result()
	if err != nil {
		return nil, err
	}
	return val, nil
}

var PluginKey = "redis"

func Init(config *Config) error {
	client = redis.NewClient(&redis.Options{
		Addr:     config.Address,
		Password: config.Password,
		DB:       config.Db,
	})
	_, err := client.Ping(ctx).Result()
	if err != nil {
		return err
	} else {
		fmt.Println("redis config load success")
		return nil
	}
}
